package com.beiding.dbrequest.utils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author 丁常磊
 * @date 2021/9/22 10:21
 */

public class QueryUtils {
    public static Map<String, String> getQuery(String text) {
        Map<String, String> metadata = new HashMap<>();
        int index = text.indexOf("?");
        if (index != -1) {
            String query = text.substring(index + 1);
            String[] split = query.split("&");
            for (String s : split) {
                String[] strings = s.split("=");
                if (strings.length == 2) {
                    metadata.put(strings[0], strings[1]);
                } else if (strings.length == 1) {
                    metadata.put(strings[0], "");
                }
            }
        }
        return metadata;
    }

    public static String getPath(String text) {
        String name;
        int index = text.indexOf("?");
        if (index != -1) {
            name = text.substring(0, index);
        } else {
            name = text;
        }
        return name;
    }

    public static String toQuery(Map<String, ?> data) {
        StringBuilder builder = new StringBuilder();
        Iterator<? extends Map.Entry<String, ?>> iterator = data.entrySet().iterator();
        if (iterator.hasNext()) {
            Map.Entry<String, ?> entry = iterator.next();
            builder.append(entry.getKey()).append("=").append(entry.getValue() == null ? "" : entry.getValue());
            while (iterator.hasNext()) {
                entry = iterator.next();
                builder.append("&").append(entry.getKey()).append("=").append(entry.getValue() == null ? "" : entry.getValue());
            }
        }
        return builder.toString();
    }

}
